package com.hera.base.web.vaadin.mantenimiento;

import static com.hera.base.util.InputData.getIntegerData;
import static com.hera.base.util.InputData.getObjectData;
import static com.hera.base.util.InputData.getStringData;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.hera.base.util.Constantes;
import com.hera.base.util.FiltroDTO;
import com.hera.base.util.TableCustom;
import com.hera.base.web.BaseUI;
import com.hera.base.web.MantenimientoMaestroDetalle;
import com.hera.process.config.domain.Condition;
import com.hera.process.workflow.domain.Process;
import com.hera.process.config.domain.ParameterDetail;
import com.hera.process.config.rest.delegate.ConfigDelegate;
import com.hera.process.config.rest.delegate.WorkflowDelegate;
import com.hera.process.form.domain.FormField;
import com.hera.process.workflow.domain.StageRollup;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.event.FieldEvents.TextChangeEvent;
import com.vaadin.event.FieldEvents.TextChangeListener;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

public class ConditionUI extends BaseUI implements MantenimientoMaestroDetalle,ClickListener {

	/*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */

	@AutoGenerated
	private VerticalLayout mainLayout;
	@AutoGenerated
	private VerticalLayout verticalLayout_1;
	@AutoGenerated
	private HorizontalLayout lytMaestro;
	@AutoGenerated
	private VerticalLayout pnlFormulario;
	@AutoGenerated
	private HorizontalLayout hlyBotonera;
	@AutoGenerated
	private Button btnEliminar;
	@AutoGenerated
	private Button btnNuevo;
	@AutoGenerated
	private ComboBox cmbNextConector;
	@AutoGenerated
	private TextField txtPrioridad;
	@AutoGenerated
	private TextField txtValueRight;
	@AutoGenerated
	private ComboBox cmbValueRight;
	@AutoGenerated
	private ComboBox cmbTypeRight;
	@AutoGenerated
	private ComboBox cmbOperador;
	@AutoGenerated
	private TextField txtValueLeft;
	@AutoGenerated
	private ComboBox cmbValueLeft;
	@AutoGenerated
	private ComboBox cmbTypeLeft;
	@AutoGenerated
	private Label lbltitulo;
	@AutoGenerated
	private HorizontalLayout lytTablaMaestra;
	@AutoGenerated
	private TableCustom tblfMaestro;
	/**
	 * 
	 */
	private static final long serialVersionUID = -6181728914647084015L;
	//private Stage stage;
	//private Process process;
	private StageRollup stageRollup;
	/**
	 * The constructor should first build the main layout, set the
	 * composition root and then do any custom initialization.
	 *
	 * The constructor will not be automatically regenerated by the
	 * visual editor.
	 */
	public ConditionUI() {
		buildMainLayout();
		setCompositionRoot(mainLayout);
	}
	
	public ConditionUI(StageRollup stageRollup, Process process) {
		buildMainLayout();
		setCompositionRoot(mainLayout);
		//this.stage = stage;
		this.process = process;
		this.stageRollup = stageRollup;
	}
	
	

	private static final Logger log = Logger.getLogger(ConditionUI.class);
	
	@Autowired
	ConfigDelegate configDelegate;
	@Autowired
	WorkflowDelegate workflowDelegate;
	
	boolean esNuevo;
	boolean esNuevoDetalle;
	Condition condition;
	Process process;
	List<FormField> listFormFieldProcess = null;
	
	@Override
	public void buttonClick(ClickEvent event) {
		if(event.getButton().equals(btnEliminar)){
			eliminarMaestro();
		}else if(event.getButton().equals(btnNuevo)){
			guardarMaestro();
		}
		
	}

	@Override
	public void cargarFormulario() {
	
		txtPrioridad.setNullRepresentation("");
		
		log.info("INCIO +++++++++");
		esNuevo = true;
		condition = null;

		btnEliminar.setVisible(false);
		btnEliminar.addClickListener(this);
		
		
		btnNuevo.setVisible(false);
		btnNuevo.addClickListener(this);
		btnNuevo.setCaption("Nuevo");
				
		BeanItemContainer<ParameterDetail> type = new BeanItemContainer<ParameterDetail>(ParameterDetail.class);
		ParameterDetail listsDetail = new ParameterDetail();
		listsDetail.setIdParameterDetail(Constantes.TIPO_OPERANDO_CONDICION.ID);
		type.addAll(configDelegate.findDetailList(listsDetail));
		cmbTypeLeft.setContainerDataSource(type);
		cmbTypeLeft.setItemCaptionPropertyId("name");
		cmbTypeLeft.setInputPrompt("Tipo");
		cmbTypeLeft.setImmediate(true);
		
		cmbValueLeft.setInputPrompt("Valor");
		txtValueLeft.setInputPrompt("Valor");
		txtValueLeft.setVisible(false);
		
		cmbTypeRight.setContainerDataSource(type);
		cmbTypeRight.setItemCaptionPropertyId("name");
		cmbTypeRight.setInputPrompt("Tipo");
		cmbTypeRight.setImmediate(true);
		
		cmbValueRight.setInputPrompt("Valor");
		txtValueRight.setInputPrompt("Valor");
		txtValueRight.setVisible(false);
		
		BeanItemContainer<ParameterDetail> type1 = new BeanItemContainer<ParameterDetail>(ParameterDetail.class);
		ParameterDetail listsDetail1 = new ParameterDetail();
		listsDetail1.setIdParameterDetail(Constantes.TIPO_OPERADOR_CONDICION.ID);
		type1.addAll(configDelegate.findDetailList(listsDetail1));
		cmbOperador.setContainerDataSource(type1);
		cmbOperador.setItemCaptionPropertyId("name");
		cmbOperador.setInputPrompt("Operador");
		cmbOperador.setImmediate(true);
		
		BeanItemContainer<ParameterDetail> type2 = new BeanItemContainer<ParameterDetail>(ParameterDetail.class);
		ParameterDetail listsDetail2 = new ParameterDetail();
		listsDetail2.setIdParameterDetail(Constantes.TIPO_CONECTOR_CONDICION.ID);
		type2.addAll(configDelegate.findDetailList(listsDetail2));
		cmbNextConector.setContainerDataSource(type2);
		cmbNextConector.setItemCaptionPropertyId("name");
		cmbNextConector.setInputPrompt("Conector");
		cmbNextConector.setImmediate(true);
		
		listFormFieldProcess = workflowDelegate.findAllFormFieldInProcess(process);
		BeanItemContainer<FormField> type3 = new BeanItemContainer<FormField>(FormField.class);		
		type3.addAll(listFormFieldProcess);
		
		cmbValueLeft.setContainerDataSource(type3);
		cmbValueRight.setContainerDataSource(type3);
		
		cmbValueLeft.setItemCaptionPropertyId("name");
		cmbValueRight.setItemCaptionPropertyId("name");
		
		//tblfMaestro.setTitulo(" Lista Formularios del Stage " + stage.getName());
		tblfMaestro.setHeight("150px");
		
		tblfMaestro.addColumn("valueLeft", "Operando Izq.", 100, true, String.class);
		tblfMaestro.addColumn("operador.name", "Signo", 50, true, String.class);
		tblfMaestro.addColumn("valueRight", "Operando Der.", 100, true, String.class);
		
		tblfMaestro.construir();
		tblfMaestro.addTextChangeListener(new TextChangeListener() {
			private static final long serialVersionUID = 1L;

			@Override
			public void textChange(TextChangeEvent event) {
				buscarMaestro(event);
				
			}
		});
		
		tblfMaestro.addValueChangeListener(new ValueChangeListener() {
			private static final long serialVersionUID = 1L;
			
			@Override
			public void valueChange(ValueChangeEvent event) {
				condition = (Condition)tblfMaestro.getSelectedItem(event);
				esNuevo = (condition==null);
				tblfMaestro.limpiarFiltro();
				if(esNuevo){
					limpiarMaestro();
					btnEliminar.setVisible(false);
				}else{
					btnEliminar.setVisible(true);
					btnNuevo.setVisible(true);
					btnNuevo.setCaption("Modificar");
					
					cmbTypeLeft.setValue(condition.getTypeLeft());
					cmbTypeRight.setValue(condition.getTypeRight());
					cmbOperador.setValue(condition.getOperador());
					cmbNextConector.setValue(condition.getNextConector());
					
					if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_FIJO.equals(((ParameterDetail)cmbTypeLeft.getValue()).getIdParameterDetail())){
						txtValueLeft.setValue(condition.getValueLeft());					
					}else if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_VARIABLE.equals(((ParameterDetail)cmbTypeLeft.getValue()).getIdParameterDetail())){						
						cmbValueLeft.setValue(condition.getFormFieldLeft());
					}
					
					if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_FIJO.equals(((ParameterDetail)cmbTypeRight.getValue()).getIdParameterDetail())){
						txtValueRight.setValue(condition.getValueRight());					
					}else if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_VARIABLE.equals(((ParameterDetail)cmbTypeRight.getValue()).getIdParameterDetail())){						
						cmbValueRight.setValue(condition.getFormFieldRight());
					}
					
					txtPrioridad.setValue(""+condition.getSecuence());
				}
			}
		});
		
		cmbTypeLeft.addValueChangeListener(new Property.ValueChangeListener() {		    
			private static final long serialVersionUID = 519197261448804864L;
			public void valueChange(ValueChangeEvent event) {
				if(cmbTypeLeft.getValue() != null){
					if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_FIJO.equals(((ParameterDetail)cmbTypeLeft.getValue()).getIdParameterDetail())){
						txtValueLeft.setVisible(true);
						cmbValueLeft.setVisible(false);
						txtValueLeft.setValue("");
					}else if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_VARIABLE.equals(((ParameterDetail)cmbTypeLeft.getValue()).getIdParameterDetail())){
						txtValueLeft.setVisible(false);
						cmbValueLeft.setVisible(true);
						cmbValueLeft.setValue(null);						
					}
				}
			}
		});
		
		cmbTypeRight.addValueChangeListener(new Property.ValueChangeListener() {		    
			private static final long serialVersionUID = 5191972614488044L;
			public void valueChange(ValueChangeEvent event) {
				if(cmbTypeRight.getValue() != null){
					if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_FIJO.equals(((ParameterDetail)cmbTypeRight.getValue()).getIdParameterDetail())){
						txtValueRight.setVisible(true);
						cmbValueRight.setVisible(false);
						txtValueRight.setValue("");
					}else if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_VARIABLE.equals(((ParameterDetail)cmbTypeRight.getValue()).getIdParameterDetail())){
						txtValueRight.setVisible(false);
						cmbValueRight.setVisible(true);
						cmbValueRight.setValue(null);
					}
				}
			}
		});
		
	}

	@Override
	public void buscarMaestro() {
		buscarMaestro(null);
		
	}

	@Override
	public void buscarMaestro(TextChangeEvent event) {
		log.info("inicio Buscar condition");
		//FiltroDTO filtroDTO = tblfMaestro.getFiltroDTO(event);
		FiltroDTO filtroDTO = new FiltroDTO();
		filtroDTO.addParametro("stageRollup.idStageRollup", stageRollup.getIdStageRollup());
		List<Condition> lstCondition = configDelegate.findAllConditions(filtroDTO);
		tblfMaestro.setLstData(lstCondition);
		limpiarMaestro();
		log.info("fin condition");
	}

	@Override
	public void limpiarMaestro() {
		log.info("inicio limpiarMaestro");
		btnNuevo.setVisible(true);
		btnNuevo.setCaption("Nuevo");
		
		cmbTypeLeft.setValue(null);
		cmbValueLeft.setVisible(true);
		cmbValueLeft.setValue(null);
		txtValueLeft.setVisible(false);
		txtValueLeft.setValue("");		
		
		cmbTypeRight.setValue(null);
		cmbValueRight.setVisible(true);
		cmbValueRight.setValue(null);
		txtValueRight.setVisible(false);
		txtValueRight.setValue("");
		txtPrioridad.setValue("");
		
		cmbOperador.setValue(null);
		cmbNextConector.setValue(null);
	
			
		log.info("fin limpiarMaestro");
		
	}

	@Override
	public void eliminarMaestro() {
		
		log.info("inicio eliminarMaestro");
		configDelegate.deleteCondition(condition);
		buscarMaestro();
		limpiarMaestro();
		log.info("fin eliminarMaestro");	
		
	}

	@Override
	public void guardarMaestro() {
		
		log.info("inicio guardarMaestro");
		if(esNuevo){
			condition=new Condition();
			obtenerDatosFormulario(condition);
			condition.setStageRollup(stageRollup);
			
			configDelegate.createCondition(condition);
		}else{
			obtenerDatosFormulario(condition);
			configDelegate.updateCondition(condition);
		}
		limpiarMaestro();
		buscarMaestro();
		log.info("fin guardarMaestro");
	}

	@Override
	public void buscarDetalle() {
		
		
	}

	@Override
	public void buscarDetalle(TextChangeEvent event) {
		
		
	}

	@Override
	public void limpiarDetalle() {
		
		
	}

	@Override
	public void eliminarDetalle() {
		
		
	}

	@Override
	public void guardarDetalle() {
		
		
	}

	@Override
	protected void postConstruct() {
		cargarFormulario();
		buscarMaestro();
		
	}

	private void obtenerDatosFormulario(Condition condition) {
		condition.setTypeLeft(getObjectData(cmbTypeLeft, ParameterDetail.class, "Tipo Izq."));
		condition.setTypeRight(getObjectData(cmbTypeRight, ParameterDetail.class, "Tipo Der."));
		condition.setSecuence(getIntegerData(txtPrioridad, "Secuencia"));
		condition.setOperador(getObjectData(cmbOperador, ParameterDetail.class, "Operador"));
		condition.setNextConector(getObjectData(cmbNextConector, ParameterDetail.class, "Conector"));
		
		if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_FIJO.equals(((ParameterDetail)cmbTypeLeft.getValue()).getIdParameterDetail())){
			condition.setValueLeft(getStringData(txtValueLeft, "Valor Izq."));
		}else if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_VARIABLE.equals(((ParameterDetail)cmbTypeLeft.getValue()).getIdParameterDetail())){
			condition.setIdRefValueLeft(getObjectData(cmbValueLeft, FormField.class, "Valor Izq.").getIdField());
			condition.setValueLeft("@@" + getObjectData(cmbValueLeft, FormField.class, "Valor Izq.").getName());
		}
		if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_FIJO.equals(((ParameterDetail)cmbTypeRight.getValue()).getIdParameterDetail())){
			condition.setValueRight(getStringData(txtValueRight, "Valor Der."));
		}else if(Constantes.TIPO_OPERANDO_CONDICION.OPERANDO_VARIABLE.equals(((ParameterDetail)cmbTypeRight.getValue()).getIdParameterDetail())){
			condition.setIdRefValueRight(getObjectData(cmbValueRight, FormField.class, "Valor Der.").getIdField());
			condition.setValueRight("@@" + getObjectData(cmbValueRight, FormField.class, "Valor Der.").getName());
		}
	}

@AutoGenerated
private VerticalLayout buildMainLayout() {
	// common part: create layout
	mainLayout = new VerticalLayout();
	mainLayout.setImmediate(false);
	mainLayout.setWidth("-1px");
	mainLayout.setHeight("-1px");
	mainLayout.setMargin(false);
	
	// top-level component properties
	setWidth("-1px");
	setHeight("-1px");
	
	// verticalLayout_1
	verticalLayout_1 = buildVerticalLayout_1();
	mainLayout.addComponent(verticalLayout_1);
	
	return mainLayout;
}

@AutoGenerated
private VerticalLayout buildVerticalLayout_1() {
	// common part: create layout
	verticalLayout_1 = new VerticalLayout();
	verticalLayout_1.setImmediate(false);
	verticalLayout_1.setWidth("-1px");
	verticalLayout_1.setHeight("-1px");
	verticalLayout_1.setMargin(false);
	verticalLayout_1.setSpacing(true);
	
	// lytMaestro
	lytMaestro = buildLytMaestro();
	verticalLayout_1.addComponent(lytMaestro);
	
	return verticalLayout_1;
}

@AutoGenerated
private HorizontalLayout buildLytMaestro() {
	// common part: create layout
	lytMaestro = new HorizontalLayout();
	lytMaestro.setImmediate(false);
	lytMaestro.setWidth("-1px");
	lytMaestro.setHeight("-1px");
	lytMaestro.setMargin(false);
	lytMaestro.setSpacing(true);
	
	// lytTablaMaestra
	lytTablaMaestra = buildLytTablaMaestra();
	lytMaestro.addComponent(lytTablaMaestra);
	
	// pnlFormulario
	pnlFormulario = buildPnlFormulario();
	lytMaestro.addComponent(pnlFormulario);
	
	return lytMaestro;
}

@AutoGenerated
private HorizontalLayout buildLytTablaMaestra() {
	// common part: create layout
	lytTablaMaestra = new HorizontalLayout();
	lytTablaMaestra.setImmediate(false);
	lytTablaMaestra.setWidth("320px");
	lytTablaMaestra.setHeight("-1px");
	lytTablaMaestra.setMargin(false);
	
	// tblfMaestro
	tblfMaestro = new TableCustom();
	tblfMaestro.setImmediate(false);
	tblfMaestro.setWidth("-1px");
	tblfMaestro.setHeight("-1px");
	lytTablaMaestra.addComponent(tblfMaestro);
	
	return lytTablaMaestra;
}

@AutoGenerated
private VerticalLayout buildPnlFormulario() {
	// common part: create layout
	pnlFormulario = new VerticalLayout();
	pnlFormulario.setImmediate(false);
	pnlFormulario.setWidth("-1px");
	pnlFormulario.setHeight("-1px");
	pnlFormulario.setMargin(false);
	pnlFormulario.setSpacing(true);
	
	// lbltitulo
	lbltitulo = new Label();
	lbltitulo.setStyleName("titulo");
	lbltitulo.setImmediate(false);
	lbltitulo.setWidth("-1px");
	lbltitulo.setHeight("-1px");
	lbltitulo.setValue("Condicion");
	pnlFormulario.addComponent(lbltitulo);
	pnlFormulario.setComponentAlignment(lbltitulo, new Alignment(20));
	
	// cmbTypeLeft
	cmbTypeLeft = new ComboBox();
	cmbTypeLeft.setStyleName("fieldRequired");
	cmbTypeLeft.setImmediate(false);
	cmbTypeLeft.setDescription("Tipo");
	cmbTypeLeft.setWidth("-1px");
	cmbTypeLeft.setHeight("-1px");
	pnlFormulario.addComponent(cmbTypeLeft);
	
	// cmbValueLeft
	cmbValueLeft = new ComboBox();
	cmbValueLeft.setStyleName("fieldRequired");
	cmbValueLeft.setImmediate(false);
	cmbValueLeft.setDescription("Value");
	cmbValueLeft.setWidth("-1px");
	cmbValueLeft.setHeight("-1px");
	pnlFormulario.addComponent(cmbValueLeft);
	
	// txtValueLeft
	txtValueLeft = new TextField();
	txtValueLeft.setStyleName("fieldRequired");
	txtValueLeft.setImmediate(false);
	txtValueLeft.setDescription("Valor");
	txtValueLeft.setWidth("-1px");
	txtValueLeft.setHeight("-1px");
	txtValueLeft.setInputPrompt("Valor");
	pnlFormulario.addComponent(txtValueLeft);
	
	// cmbOperador
	cmbOperador = new ComboBox();
	cmbOperador.setStyleName("fieldRequired");
	cmbOperador.setImmediate(false);
	cmbOperador.setDescription("Tipo");
	cmbOperador.setWidth("-1px");
	cmbOperador.setHeight("-1px");
	pnlFormulario.addComponent(cmbOperador);
	
	// cmbTypeRight
	cmbTypeRight = new ComboBox();
	cmbTypeRight.setStyleName("fieldRequired");
	cmbTypeRight.setImmediate(false);
	cmbTypeRight.setDescription("Tipo");
	cmbTypeRight.setWidth("-1px");
	cmbTypeRight.setHeight("-1px");
	pnlFormulario.addComponent(cmbTypeRight);
	
	// cmbValueRight
	cmbValueRight = new ComboBox();
	cmbValueRight.setStyleName("fieldRequired");
	cmbValueRight.setImmediate(false);
	cmbValueRight.setDescription("Tipo");
	cmbValueRight.setWidth("-1px");
	cmbValueRight.setHeight("-1px");
	pnlFormulario.addComponent(cmbValueRight);
	
	// txtValueRight
	txtValueRight = new TextField();
	txtValueRight.setStyleName("fieldRequired");
	txtValueRight.setImmediate(false);
	txtValueRight.setDescription("Valor");
	txtValueRight.setWidth("-1px");
	txtValueRight.setHeight("-1px");
	txtValueRight.setInputPrompt("Valor");
	pnlFormulario.addComponent(txtValueRight);
	
	// txtPrioridad
	txtPrioridad = new TextField();
	txtPrioridad.setStyleName("fieldRequired");
	txtPrioridad.setImmediate(false);
	txtPrioridad.setDescription("Prioridad");
	txtPrioridad.setWidth("-1px");
	txtPrioridad.setHeight("-1px");
	txtPrioridad.setInputPrompt("Prioridad");
	pnlFormulario.addComponent(txtPrioridad);
	
	// cmbNextConector
	cmbNextConector = new ComboBox();
	cmbNextConector.setImmediate(false);
	cmbNextConector.setDescription("Tipo");
	cmbNextConector.setWidth("-1px");
	cmbNextConector.setHeight("-1px");
	pnlFormulario.addComponent(cmbNextConector);
	
	// hlyBotonera
	hlyBotonera = buildHlyBotonera();
	pnlFormulario.addComponent(hlyBotonera);
	
	return pnlFormulario;
}

@AutoGenerated
private HorizontalLayout buildHlyBotonera() {
	// common part: create layout
	hlyBotonera = new HorizontalLayout();
	hlyBotonera.setImmediate(false);
	hlyBotonera.setWidth("-1px");
	hlyBotonera.setHeight("-1px");
	hlyBotonera.setMargin(false);
	hlyBotonera.setSpacing(true);
	
	// btnNuevo
	btnNuevo = new Button();
	btnNuevo.setCaption("Nuevo");
	btnNuevo.setImmediate(true);
	btnNuevo.setWidth("-1px");
	btnNuevo.setHeight("-1px");
	hlyBotonera.addComponent(btnNuevo);
	
	// btnEliminar
	btnEliminar = new Button();
	btnEliminar.setCaption("Eliminar");
	btnEliminar.setImmediate(true);
	btnEliminar.setWidth("-1px");
	btnEliminar.setHeight("-1px");
	hlyBotonera.addComponent(btnEliminar);
	
	return hlyBotonera;
}
	
	
}
